//
//  serviceGetPlayerStatus.m
//  upnpxdemo
//
//  Created by 赵帅 on 13-9-1.
//  Copyright (c) 2013年 wiimu.inc. All rights reserved.
//

#import "serviceGetPlayerStatus.h"
#import "privateJSONParser.h"

@implementation serviceGetPlayerStatus
#pragma mark Initialization & Deallocation

-(id)initWithDelegate:(id <serviceGetPlayerStatusDelegate>) aDelegate
{
	self = [super init];
	if (self)
	{
		self.m_serviceHandler = aDelegate;
	}
    
	return self;
}



#pragma mark -
#pragma mark Configure the request
-(NSURL*)targetURL
{
    NSString * ipStr = [m_dicSendData objectForKey:@"baseurl"];
    NSString *urlStr = [NSString stringWithFormat:@"%@/httpapi.asp?command=getPlayerStatus",ipStr];
	NSURL *theUrl = [[NSURL alloc] initWithString:urlStr];
	
	return theUrl;
}

-(void)configureRequest
{
	[super configureRequest];
	[m_request setRequestMethod:@"GET"];
}

#pragma mark -
#pragma mark Parse the response
-(void)parseResponseData:(NSData *)data
{
	[super parseResponseData:data];
    
	NSMutableString * retStr = [NSMutableString stringWithString:m_request.responseString];
	
    if(retStr == nil)
    {
        [m_dicReceiveData setObject:SERVICE_FAIL forKey:@"responsestatus"];
        return;
    }
    
    [retStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [retStr length])];
    
    if([retStr objectFromJSONString] != nil)
    {
        [m_dicReceiveData addEntriesFromDictionary:[retStr objectFromJSONString]];
    }
    else
    {
        NSString* sub = nil;
        privateJSONDParser *parser = [[privateJSONDParser alloc] initWithObjectAndDic:retStr withDic:m_dicReceiveData];
        
        sub = [parser parseObject:@"mode"];
        if(sub)
        {
            sub = [parser parseObject:@"status"];
            if(sub)
            {
                sub = [parser parseObject:@"curpos"];
                if(sub)
                {
                    sub = [parser parseObject:@"totlen"];
                    if(sub)
                    {
                        sub = [parser parseObject:@"Title"];
                        if(sub)
                        {
                            sub = [parser parseObject:@"Artist"];
                            if(sub)
                            {
                                sub = [parser parseObject:@"Album"];
                                if(sub)
                                {
                                    sub = [parser parseObject:@"Year"];
                                    if(sub)
                                    {
                                        sub = [parser parseObject:@"Track"];
                                        if(sub)
                                        {
                                            sub = [parser parseObject:@"Genre"];
                                            if(sub)
                                            {
                                                sub = [parser parseObject:@"locallistflag"];
                                                if(sub)
                                                {
                                                    sub = [parser parseObject:@"locallistfile"];
                                                    if(sub)
                                                    {
                                                        sub = [parser parseObject:@"vol"];
                                                        if(sub)
                                                        {
                                                            sub = [parser parseObject:@"mute"];
                                                            if(sub)
                                                            {
                                                                sub = [parser parseObject:@"uri"];
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        
        if(sub == nil)
        {
            //haiyong 能不能定义另外一个变量，例如PARSE_FAIL，把这种错误与连接错误区分开来，只有连接错误才返回设备列表，
            [m_dicReceiveData setObject:SERVICE_FAIL forKey:@"responsestatus"];
            return;
        }
    }
    
    //title 转码
    NSString * str = [self decode:[m_dicReceiveData[@"Title"] uppercaseString]];
    if([str length] != 0)
    {
        [m_dicReceiveData setObject:str forKey:@"Title"];
    }
}

-(NSString *)decode:(NSString*)hexStr
{
    if([hexStr length] == 0 || ([hexStr length])%2 != 0 )
    {
        return nil;
    }
    
    int byteLength = [hexStr length] /2;
    char * bytes = malloc(byteLength);
    
    
    int temp=0;
    for(int i=0;i<byteLength;i++)
    {
        temp = [self hex2Dec:[hexStr characterAtIndex:2*i]*16+[hexStr characterAtIndex:2*i+1]];
        temp = [self hex2Dec:[hexStr characterAtIndex:2*i]]*16+[self hex2Dec:[hexStr characterAtIndex:2*i+1]];
        bytes[i]=(char)( temp<128 ? temp : temp-256 ) ;
    }
    
    NSStringEncoding gbkEncoding =CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
    NSString*pageSource = [[NSString alloc] initWithBytes:bytes length:byteLength encoding:gbkEncoding];
    
    return pageSource;
}

-(int)hex2Dec:(char)ch
{
	if(ch == '0') return 0;
	if(ch == '1') return 1;
	if(ch == '2') return 2;
	if(ch == '3') return 3;
	if(ch == '4') return 4;
	if(ch == '5') return 5;
	if(ch == '6') return 6;
	if(ch == '7') return 7;
	if(ch == '8') return 8;
	if(ch == '9') return 9;
	if(ch == 'a') return 10;
	if(ch == 'A') return 10;
	if(ch == 'B') return 11;
	if(ch == 'b') return 11;
	if(ch == 'C') return 12;
	if(ch == 'c') return 12;
	if(ch == 'D') return 13;
	if(ch == 'd') return 13;
	if(ch == 'E') return 14;
	if(ch == 'e') return 14;
	if(ch == 'F') return 15;
	if(ch == 'f') return 15;
	else return -1;
}

#pragma mark -
#pragma mark Pass Data To UI
-(void)passDataOut
{
	[super passDataOut];
	
	if (nil != self.m_serviceHandler
		&& [self.m_serviceHandler respondsToSelector:@selector(serviceGetPlayerStatusCallBack:)])
	{
        [self.m_serviceHandler performSelectorOnMainThread:@selector(serviceGetPlayerStatusCallBack:) withObject:m_dicReceiveData waitUntilDone:YES];
	}
}
@end
